* Create connected set for hospitals with PCI facilities throughout the period (used to create columns 1 and 2 of App Table A4 and Figure A5)

use "$savedata/ami_analysis_mainspef.dta", clear

gen pat_pci = 0
replace pat_pci = 1 if substr(opertn_01,1,3)=="K49" | substr(opertn_01,1,3)=="K50" | substr(opertn_01,1,3)=="K75"

gen one = 1

collapse (sum) one pat_pci, by(trust_code finyear)

keep if pat_pci>10

save "$savedata/pci_hospitalyear_list.dta", replace


* Use this list of hospitals to create dataset we want to use to analyse hospitals doing PCIs throughout the period

use "$savedata/ami_analysis_mainspef.dta", clear

drop if derv_age<35

merge m:1 trust_code finyear using "$savedata/pci_hospitalyear_list.dta", keepusing(pat_pci)
keep if _merge==3
drop _merge

egen hosp_vol_year = sum(ami), by(trust_code finyear)

* Treat at least 100 heart attack patients in a year to be included in the data
keep if hosp_vol_year>99


* Now put restrictions on the minimum number of patients treated by docs in each hospital 
egen vol = sum(ami), by(pconsult)
egen vol_trust = sum(ami), by(pconsult trust_code)

drop if vol_trust<10

* Also check when doing this by year
egen vol_year = sum(ami), by(pconsult finyear)

egen vol_trust_year = sum(ami), by(pconsult trust_code finyear)

* Make restrictions by minimum volumes of consultant-trust pairs
foreach x in 10 25 50 100{
	
preserve
* Only want to be linked by docs who treat x or more patients in a given hospital
collapse (sum) ami, by(trust_code pconsult)

* This is new as of 14th July 2024
keep if ami>=`x'

egen constotal = sum(ami), by(pconsult)
rename ami trust_constotal
*egen trust_constotal = sum(ami), by(pconsult trust_code)

* How to connect?
** start with connection being that doctors work in at least 2 hospitals; with a minimum volume in total

* Number of hospitals worked in a given year
bys pconsult: gen x=_n
egen total_trusts_worked_in = max(x), by(pconsult)

* Keep only the connectors (those in more than one hospital in a given year)
keep if total_trusts>1

* Now keep only those who do a minimum of 10 or more
keep if trust_constotal>`x'

* for graphs, want to plot these
egen mincheck = min(trust_constotal), by(pconsult)
egen maxcheck = max(trust_constotal), by(pconsult)

* This is the original connected set

gen akm_set_mainspef`x'_pci = 1
gen akm_connectors`x'_pci = 1
egen akm_connecting_pats`x'_pci = sum(trust_constotal), by(trust_code)

collapse (max) akm_set_mainspef`x'_pci (sum) akm_connectors`x'_pci akm_connecting_pats`x'_pci, by(trust_code)

save "$savedata/connect_total`x'_pcihosps.dta", replace
count

restore
}
